package wty;

import javax.swing.*;
import java.sql.*;

public class Register_SQL {
    //本函数用来对于注册进行数据库操作
    public static void mysql(JTextField useNameField, JTextField userField, JPasswordField passwordField, JTextField phoneField){

        String userName = useNameField.getText().trim(); // 去除前后空格
        String user = userField.getText().trim();
        String userPassword = new String(passwordField.getPassword()).trim();
        String phone = phoneField.getText().trim();

        if (userName.isEmpty() || user.isEmpty() || userPassword.isEmpty() || phone.isEmpty()) {
            System.out.println("有空值");
            return; // 终止方法执行
        }

        try {
            com.mysql.cj.jdbc.Driver mysqlDriver = new com.mysql.cj.jdbc.Driver();
            DriverManager.registerDriver(mysqlDriver);
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("未能正常加载MySQL驱动");
        }
        // 2. 连接到数据库服务
        String url = "jdbc:mysql://localhost:3306/project";
        String username = "root";
        String password = "root";
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.err.println("数据库在连接期间，出现错误！");
        }

        // 进行插入的SQL 语句
        String sql = "INSERT INTO users (Name,ID,Password,PhoneNum) VALUES (?, ?, ?, ?)";

        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, user);
            preparedStatement.setString(3, userPassword);
            preparedStatement.setString(4, phone);

            preparedStatement.executeUpdate();
//            System.out.println(rowsAffected + " 行已插入.");
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("插入数据时出现错误！");
        } finally {
            // 关闭资源
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.err.println("在执行数据库关闭动作时，出现错误！");
            }
        }
    }
}
